<template>
  <div class="favorites-container">
    <el-card class="favorites-card">
      <template #header>
        <div class="card-header">
          <h2>我的收藏</h2>
        </div>
      </template>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <div v-else-if="favorites.length === 0" class="empty-container">
        <el-empty description="暂无收藏的课程" />
        <el-button type="primary" @click="goToHome">去浏览课程</el-button>
      </div>
      
      <div v-else class="favorites-list">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="lesson in favorites" :key="lesson.id" class="lesson-col">
            <el-card class="lesson-card" @click="viewLesson(lesson)">
              <div class="lesson-cover">
                <img :src="lesson.coverImg" :alt="lesson.title" />
              </div>
              <div class="lesson-info">
                <h3 class="lesson-title">{{ lesson.title }}</h3>
                <div class="lesson-meta">
                  <span class="lesson-author">
                    <el-icon><User /></el-icon>
                    {{ lesson.createUserName }}
                  </span>
                  <span class="lesson-stats">
                    <el-icon><Star /></el-icon>
                    {{ lesson.favoriteCount || 0 }}
                  </span>
                  <span class="lesson-stats">
                    <el-icon><Collection /></el-icon>
                    {{ lesson.likeCount || 0 }}
                  </span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-card>
    
    <!-- 课程详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="课程详情"
      width="70%"
      :destroy-on-close="true"
    >
      <template v-if="currentLesson">
        <div class="lesson-detail">
          <h2>{{ currentLesson.title }}</h2>
          <div class="detail-meta">
            <span>分类：{{ currentLesson.categoryName }}</span>
            <span>作者：{{ currentLesson.createUserName }}</span>
            <span>发布时间：{{ currentLesson.createTime }}</span>
            <span>状态：{{ currentLesson.state }}</span>
          </div>
          <div class="detail-actions">
            <el-button 
              :icon="isLiked ? CollectionTag : Collection" 
              :type="isLiked ? 'primary' : 'default'"
              @click.stop="toggleLike">
              {{ isLiked ? '已点赞' : '点赞' }} ({{ likeCount }})
            </el-button>
            <el-button 
              :icon="isFavorited ? StarFilled : Star" 
              :type="isFavorited ? 'warning' : 'default'"
              @click.stop="toggleFavorite">
              {{ isFavorited ? '已收藏' : '收藏' }} ({{ favoriteCount }})
            </el-button>
          </div>
          <div class="detail-video">
            <video 
              v-if="currentLesson.videoUrl" 
              :src="currentLesson.videoUrl" 
              controls
              preload="metadata"
              style="width: 100%; max-height: 400px;">
              您的浏览器不支持视频播放
            </video>
          </div>
          <div class="detail-content" v-html="currentLesson.content"></div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  getUserFavoritesService, 
  lessonLikeService, 
  lessonUnlikeService, 
  lessonFavoriteService, 
  lessonUnfavoriteService, 
  getLessonLikeStatusService, 
  getLessonFavoriteStatusService, 
  getLessonLikeCountService, 
  getLessonFavoriteCountService 
} from '@/api/lesson'
import { User, Star, Collection, CollectionTag, StarFilled } from '@element-plus/icons-vue'

const router = useRouter()
const favorites = ref([])
const loading = ref(true)

// 控制课程详情对话框的显示
const dialogVisible = ref(false)
// 当前选中的课程
const currentLesson = ref(null)

// 点赞和收藏状态
const isLiked = ref(false)
const isFavorited = ref(false)
const likeCount = ref(0)
const favoriteCount = ref(0)

// 获取收藏列表
const fetchFavorites = async () => {
  loading.value = true
  try {
    const res = await getUserFavoritesService()
    if (res.code === 0) {
      favorites.value = res.data || []
    } else {
      ElMessage.error(res.msg || '获取收藏列表失败')
    }
  } catch (error) {
    console.error('获取收藏列表出错:', error)
    ElMessage.error('获取收藏列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 查看课程详情
const viewLesson = async (lesson) => {
  currentLesson.value = lesson
  dialogVisible.value = true
  
  // 获取点赞和收藏状态
  await getLikeStatus(lesson.id)
  await getFavoriteStatus(lesson.id)
  
  // 获取点赞和收藏数量
  await getLikeCount(lesson.id)
  await getFavoriteCount(lesson.id)
}

// 获取点赞状态
const getLikeStatus = async (lessonId) => {
  try {
    const result = await getLessonLikeStatusService(lessonId)
    if (result.code === 0) {
      isLiked.value = result.data
    }
  } catch (error) {
    console.error('获取点赞状态失败:', error)
  }
}

// 获取收藏状态
const getFavoriteStatus = async (lessonId) => {
  try {
    const result = await getLessonFavoriteStatusService(lessonId)
    if (result.code === 0) {
      isFavorited.value = result.data
    }
  } catch (error) {
    console.error('获取收藏状态失败:', error)
  }
}

// 获取点赞数量
const getLikeCount = async (lessonId) => {
  try {
    const result = await getLessonLikeCountService(lessonId)
    if (result.code === 0) {
      likeCount.value = result.data
    }
  } catch (error) {
    console.error('获取点赞数量失败:', error)
  }
}

// 获取收藏数量
const getFavoriteCount = async (lessonId) => {
  try {
    const result = await getLessonFavoriteCountService(lessonId)
    if (result.code === 0) {
      favoriteCount.value = result.data
    }
  } catch (error) {
    console.error('获取收藏数量失败:', error)
  }
}

// 点赞/取消点赞课程
const toggleLike = async () => {
  if (!currentLesson.value) return
  
  try {
    if (isLiked.value) {
      // 取消点赞
      const result = await lessonUnlikeService(currentLesson.value.id)
      if (result.code === 0) {
        isLiked.value = false
        likeCount.value = Math.max(0, likeCount.value - 1)
        ElMessage.success('取消点赞成功')
      } else {
        ElMessage.error(result.msg || '取消点赞失败')
      }
    } else {
      // 点赞
      const result = await lessonLikeService(currentLesson.value.id)
      if (result.code === 0) {
        isLiked.value = true
        likeCount.value += 1
        ElMessage.success('点赞成功')
      } else {
        ElMessage.error(result.msg || '点赞失败')
      }
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 收藏/取消收藏课程
const toggleFavorite = async () => {
  if (!currentLesson.value) return
  
  try {
    if (isFavorited.value) {
      // 取消收藏
      const result = await lessonUnfavoriteService(currentLesson.value.id)
      if (result.code === 0) {
        isFavorited.value = false
        favoriteCount.value = Math.max(0, favoriteCount.value - 1)
        ElMessage.success('取消收藏成功')
        // 刷新收藏列表
        fetchFavorites()
      } else {
        ElMessage.error(result.msg || '取消收藏失败')
      }
    } else {
      // 收藏
      const result = await lessonFavoriteService(currentLesson.value.id)
      if (result.code === 0) {
        isFavorited.value = true
        favoriteCount.value += 1
        ElMessage.success('收藏成功')
      } else {
        ElMessage.error(result.msg || '收藏失败')
      }
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 跳转到首页
const goToHome = () => {
  router.push('/home')
}

onMounted(() => {
  fetchFavorites()
})
</script>

<style lang="scss" scoped>
.favorites-container {
  padding: 20px;
  min-height: calc(100vh - 120px);
}

.favorites-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  h2 {
    margin: 0;
    font-size: 20px;
    color: #303133;
  }
}

.loading-container {
  padding: 20px 0;
}

.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 0;
  
  .el-button {
    margin-top: 20px;
  }
}

.favorites-list {
  margin-top: 20px;
}

.lesson-col {
  margin-bottom: 20px;
}

.lesson-card {
  cursor: pointer;
  transition: transform 0.3s, box-shadow 0.3s;
  height: 100%;
  display: flex;
  flex-direction: column;
  
  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  }
}

.lesson-cover {
  height: 160px;
  overflow: hidden;
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.lesson-info {
  padding: 12px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.lesson-title {
  margin: 0 0 10px;
  font-size: 16px;
  font-weight: bold;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.lesson-meta {
  display: flex;
  align-items: center;
  margin-top: auto;
  color: #909399;
  font-size: 13px;
}

.lesson-author {
  display: flex;
  align-items: center;
  margin-right: 15px;
  
  .el-icon {
    margin-right: 4px;
  }
}

.lesson-stats {
  display: flex;
  align-items: center;
  margin-right: 15px;
  
  .el-icon {
    margin-right: 4px;
  }
}

.lesson-detail {
  h2 {
    margin-bottom: 20px;
    color: #303133;
  }

  .detail-meta {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;
    color: #666;
    font-size: 14px;
  }

  .detail-actions {
    margin-bottom: 20px;
    display: flex;
    gap: 15px;
    
    .el-button {
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-2px);
      }
    }
  }

  .detail-video {
    margin-bottom: 20px;
    background: #f5f5f5;
    border-radius: 4px;
    overflow: hidden;
  }

  .detail-content {
    line-height: 1.6;
    color: #303133;
  }
}
</style> 